package com.swpu.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swpu.project.common.BaseResponse;
import com.swpu.project.mapper.NativeMapper;
import com.swpu.project.model.dto.data.DataEntity;
import com.swpu.project.model.dto.data.DataEntityDto;
import com.swpu.project.model.entity.*;
import com.swpu.project.model.page.PageDto;
import com.swpu.project.model.page.PageQuery;
import com.swpu.project.service.IHeavyMetalService;
import com.swpu.project.service.IMineralService;
import com.swpu.project.service.INativeService;
import com.swpu.project.service.INonHeavyMetalService;
import com.swpu.project.strategy.FilterContext;
import com.swpu.project.util.NumberUtil;
import com.swpu.project.util.XlxsDataType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.swpu.project.util.AuthorityUtil.checkAuthority;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author swpuyanxiegroup1
 * @since 2024-07-29
 */
@Service
public class NativeServiceImpl extends ServiceImpl<NativeMapper, Native> implements INativeService
{
    @Resource
    IHeavyMetalService iHeavyMetalService;
    @Resource
    INonHeavyMetalService iNonHeavyMetalService;
    @Resource
    IMineralService iMineralService;
   @Resource
   NativeMapper nativeMapper;

    public BaseResponse addData(List<DataEntityDto> dataEntityDtos) {

        List<String> blocks= dataEntityDtos.stream().
                map(dataEntityDto -> dataEntityDto.getDataEntity().getBlockName()).
                collect(Collectors.toList());
        LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if(principal.getJudge()||!checkAuthority(blocks))
            return BaseResponse.fail("您不具有该操作的权限");

        List<Native> natives = dataEntityDtos.stream().map(dataEntityDto -> {
            DataEntity dataEntity = dataEntityDto.getDataEntity();
            return BeanUtil.copyProperties(dataEntity, Native.class);

        }).collect(Collectors.toList());

        boolean save = saveBatch(natives);
        addInform(dataEntityDtos);
        return BaseResponse.iFSuccess(save);


    }







    @Override
    public BaseResponse updateData(List<Native> aNative)
    {
        LoginUser principal = (LoginUser)SecurityContextHolder
                .getContext().getAuthentication().getPrincipal();
        List<String> blocks = aNative.stream().map(Native::getBlockName)
                .collect(Collectors.toList());

        if(principal.getJudge()||!checkAuthority(blocks))
         return BaseResponse.fail("您不具有进行该搞作的权限");




        return BaseResponse.iFSuccess(updateBatchById(aNative));
    }

   void setBlockCondition(LambdaQueryWrapper<Native> lambdaQueryWrapper)
      {
          LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
          List<String> blockNums = principal.getBlockNums();
          if(principal.getJudge())
              return;

          lambdaQueryWrapper.and(lambdaQueryWrapper1 -> {

          for (int i = 0; i <blockNums.size() ; i++) {
              String s = blockNums.get(i);
              s=s+"号区块";
              lambdaQueryWrapper1.eq(Native::getBlockName,s);
              if(i != blockNums.size()-1)
                  lambdaQueryWrapper1.or();
          }
      }
      );

      }



    @Override
    public BaseResponse   pageQuery(PageQuery pageQuery)
    {
        LambdaQueryWrapper<Native> nativeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        Map<String, String> queryBy = pageQuery.getQueryBy();
           if(queryBy!=null) {
               String blockNum = queryBy.get("blockName");

               if (StrUtil.isNotBlank(blockNum)) {
                   if (!setValidBlock(nativeLambdaQueryWrapper, blockNum))
                       return BaseResponse.fail("筛选条件有误");

               }


               queryBy.remove("blockName");
               if (!queryBy.isEmpty())
                   setOtherCondtion(nativeLambdaQueryWrapper, queryBy);

           }

        setBlockCondition(nativeLambdaQueryWrapper);
        Page page = pageQuery.setPage(pageQuery);
        page(page, nativeLambdaQueryWrapper);
        PageDto nativePageDto = new PageDto(page);
        return BaseResponse.ok(nativePageDto);

    }

    private Page setPage(PageQuery pageQuery) {
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        Page<Native> page = Page.of(pageNum, pageSize);
        pageQuery.initSortBy(page);



        return page;

    }

    private void setOtherCondtion(LambdaQueryWrapper<Native> nativeLambdaQueryWrapper, Map<String, String> queryBy)
    {
        FilterContext filterContext = FilterContext.getConText(XlxsDataType.NATIVE);
        filterContext.makeFilterCondtion(nativeLambdaQueryWrapper,queryBy);

    }


    private Boolean setValidBlock(LambdaQueryWrapper<Native> nativeLambdaQueryWrapper,String blockNum)
    {
        LoginUser principal = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> blockNums = principal.getBlockNums();
        blockNum= NumberUtil.findNumber(blockNum);
        if(blockNum==null)
            return false;


        if(!blockNum.contains(blockNum))
            return false;

      nativeLambdaQueryWrapper.likeRight(Native::getBlockName,blockNum);

        return true;
    }






    public  void addInform(List<DataEntityDto> dataEntityDtos)
   {
       List<HeavyMetal> heavyMetals = new ArrayList<>();

       List<NonHeavyMetal> nonHeavyMetals = new ArrayList<>();
       List<Mineral> minerals = new ArrayList<>();
       for (DataEntityDto dataEntityDto : dataEntityDtos)
       {
           List<HeavyMetal> heavyMetals1 = dataEntityDto.getHeavyMetals();
           List<NonHeavyMetal> nonHeavyMetals1 = dataEntityDto.getNonHeavyMetals();
           List<Mineral> minerals1 = dataEntityDto.getMinerals();
              heavyMetals.addAll(heavyMetals1);
              nonHeavyMetals.addAll(nonHeavyMetals1);
              minerals.addAll(minerals1);
       }


         iHeavyMetalService.saveBatch(heavyMetals);
         iNonHeavyMetalService.saveBatch(nonHeavyMetals);
         iMineralService.saveBatch(minerals);


   }




}
